package com.icinfo.cloud.provider.punish.fastcase.service.impl;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.http.HttpStatus;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.icinfo.cloud.common.security.util.UserUtil;
import com.icinfo.cloud.provider.common.constant.Constant;
import com.icinfo.cloud.provider.common.enums.AttachmentRequestContentTypeEnum;
import com.icinfo.cloud.provider.common.enums.DocumentKindEnum;
import com.icinfo.cloud.provider.common.enums.DocumentTemplateKindEnum;
import com.icinfo.cloud.provider.common.utils.BaseUtil;
import com.icinfo.cloud.provider.common.utils.CustomCheckParamUtil;
import com.icinfo.cloud.provider.common.utils.HeaderUtil;
import com.icinfo.cloud.provider.exception.BusinessException;
import com.icinfo.cloud.provider.peripheralinterface.regulatory.vo.PunishItemVo;
import com.icinfo.cloud.provider.punish.api.client.fastcase.FastCaseRegisterClient;
import com.icinfo.cloud.provider.punish.common.documentoperate.enums.DocumentStatusEnum;
import com.icinfo.cloud.provider.punish.common.documentoperate.enums.DocumentTypeEnum;
import com.icinfo.cloud.provider.punish.config.model.ConfigBusiParamDocumentInfo;
import com.icinfo.cloud.provider.punish.config.vo.AreaVo;
import com.icinfo.cloud.provider.punish.config.vo.ConfigFastProcedureDocumentInfoVo;
import com.icinfo.cloud.provider.punish.config.vo.ConfigFastProcedureVo;
import com.icinfo.cloud.provider.punish.dto.CaseAppendixDeleteDto;
import com.icinfo.cloud.provider.punish.dto.CaseAppendixSaveDto;
import com.icinfo.cloud.provider.punish.dto.CaseDocumentRecordSignSaveDto;
import com.icinfo.cloud.provider.punish.fasecase.dto.FastNoticeDocumentDto;
import com.icinfo.cloud.provider.punish.fastcase.dto.*;
import com.icinfo.cloud.provider.punish.fastcase.service.IFastCaseService;
import com.icinfo.cloud.provider.punish.fastcase.vo.*;
import com.icinfo.cloud.provider.punish.mapper.*;
import com.icinfo.cloud.provider.punish.service.ICaseDocumentRecordService;
import com.icinfo.cloud.provider.punish.service.ICaseMainInfoService;
import com.icinfo.cloud.provider.punish.service.IConfigBusiParamDocumentInfoService;
import com.icinfo.cloud.provider.punish.ucase.casemain.dto.CaseDocumentRecordDto;
import com.icinfo.cloud.provider.punish.ucase.casemain.enums.CaseStageEnum;
import com.icinfo.cloud.provider.punish.ucase.casemain.enums.CaseStatusEnum;
import com.icinfo.cloud.provider.punish.ucase.casemain.enums.CaseTypeEnum;
import com.icinfo.cloud.provider.punish.ucase.casemain.model.CaseAppendixRecord;
import com.icinfo.cloud.provider.punish.ucase.casemain.model.CaseDocumentRecord;
import com.icinfo.cloud.provider.punish.ucase.casemain.model.CaseMainInfo;
import com.icinfo.cloud.provider.punish.ucase.casemain.model.CaseOfflineDocumentRecord;
import com.icinfo.cloud.provider.punish.ucase.casemain.vo.CaseCurrentLinkMoreOperateVo;
import com.icinfo.cloud.provider.punish.ucase.casemain.vo.CaseCurrentLinkOperateVo;
import com.icinfo.cloud.provider.punish.ucase.caseregister.dto.CaseRegisterDetailQueryDto;
import com.icinfo.cloud.provider.punish.ucase.caseregister.dto.CaseRegisterSaveDto;
import com.icinfo.cloud.provider.punish.ucase.caseregister.vo.CaseRegisterInfoVo;
import com.icinfo.cloud.provider.punish.ucase.caseregister.vo.CaseRegisterSaveVo;
import com.icinfo.cloud.provider.punish.ucase.punishinform.dto.FastCaseAddInfoTemporaryDto;
import com.icinfo.cloud.provider.punish.ucase.punishinform.dto.InformHtmlRequest;
import com.icinfo.cloud.provider.punish.ucase.punishinform.dto.PunishInformFormDto;
import com.icinfo.cloud.provider.punish.ucase.punishinform.vo.PunishInformFormVo;
import com.icinfo.cloud.provider.punish.vo.AppInvalidCaseDetailDocumentInfoVo;
import com.icinfo.cloud.provider.punish.vo.ConfigPoliceAdjudicationVo;
import com.icinfo.cloud.xzcf.provider.member.userinfo.dto.UserDTO;
import com.icinfo.framework.common.web.Result;
import com.icinfo.framework.mybatis.mapper.entity.Example;
import com.icinfo.framework.tools.utils.MapUtils;
import com.icinfo.framework.tools.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.*;

/**
 * @Description 简案快办对应的Service接口实现类
 * @Author WangJie
 * @Date 2022/12/05
 **/
@Slf4j
@Service
public class FastCaseServiceImpl implements IFastCaseService {

    @Value("${tzService.url}")
    private String url;

    @Resource
    private CaseMainInfoMapper caseMainInfoMapper;
    @Resource
    private CaseAppendixRecordMapper caseAppendixRecordMapper;
    @Resource
    private CaseDocumentRecordMapper caseDocumentRecordMapper;

    @Resource
    private ICaseDocumentRecordService caseDocumentRecordService;

    @Resource
    private FastCaseRegisterClient fastCaseRegisterClient;
    @Resource
    private ICaseMainInfoService caseMainInfoService;
    @Resource
    private CaseOfflineDocumentRecordMapper caseOfflineDocumentRecordMapper;
    @Resource
    private IConfigBusiParamDocumentInfoService configBusiParamDocumentInfoService;
    @Resource
    private ConfigBusiParamDocumentInfoMapper configBusiParamDocumentInfoMapper;
    /**
     * 描述：附件上传通用方法
     *
     * @param saveDto 保存dto
     * @return boolean
     * @author WangJie
     * @date 2022/12/05
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean saveAppFastCaseFileCommon(AppFastCaseCommonFileSaveDto saveDto) {
        //保存附件
        UserDTO userInfo = UserUtil.getUserInfo();
        if (userInfo == null) {
            throw new com.icinfo.cloud.provider.common.exception.BusinessException("请先登录!");
        }
        String caseId = saveDto.getCaseId();
        CaseMainInfo caseMainInfo = caseMainInfoMapper.selectByPrimaryKey(caseId);
        if (CaseStatusEnum.END_CASE.getCode().equals(caseMainInfo.getCaseStatus())) {
            throw new BusinessException("案件已结案，不可再上传照片和附件！");
        }
        //保存照片
        List<CaseAppendixSaveDto> photoList = saveDto.getPhotoList();
        if (photoList.size() > 10) {
            throw new BusinessException("照片最多上传10张！");
        }
        photoList.forEach(e -> {
            CustomCheckParamUtil.doCheck(e);
            e.setAppendixTypeId(saveDto.getAppendixTypeId());
            String attachmentId = e.getId();
            if (ObjectUtils.isEmpty(attachmentId)) {
                CaseAppendixRecord appendixRecord = new CaseAppendixRecord();
                appendixRecord.setCaseId(caseId);
                BeanUtils.copyProperties(e, appendixRecord);
                appendixRecord.setId(BaseUtil.createUid());
                appendixRecord.setCaseLinkCode(caseMainInfo.getCaseCurrentLinkCode());
                appendixRecord.setCaseLinkName(caseMainInfo.getCaseCurrentLinkName());
                appendixRecord.setCaseStageCode(caseMainInfo.getCaseCurrentStageCode());
                appendixRecord.setCaseStageName(caseMainInfo.getCaseCurrentStageName());
                appendixRecord.setDocumentCatalogCode("");
                if (!ObjectUtils.isEmpty(userInfo)) {
                    appendixRecord.setUploadUserId(userInfo.getUserId() + "");
                    appendixRecord.setUploadUserName(userInfo.getRealName());
                }
                appendixRecord.setUploadTime(LocalDateTime.now());
                appendixRecord.setAppendixUrl(e.getAppendixUrl());
                appendixRecord.setIsDelete(Constant.STRING_0);
                String suffix = e.getAppendixName().substring(e.getAppendixName().lastIndexOf(".") + 1);
                if (!suffix.equals(AttachmentRequestContentTypeEnum.png.getCode())
                        &&!suffix.equals(AttachmentRequestContentTypeEnum.jpg.getCode())
                        &&!suffix.equals(AttachmentRequestContentTypeEnum.pdf.getCode())) {
                    appendixRecord.setAppendixName(saveDto.getAppendixName()+"."+e.getAppendixUrl()
                            .substring(e.getAppendixUrl().lastIndexOf(".")+1));
                } else {
                    appendixRecord.setAppendixName(saveDto.getAppendixName());
                }
                caseAppendixRecordMapper.insertSelective(appendixRecord);
            }
        });

        //保存附件
        List<CaseAppendixSaveDto> appendixSaveDtoList = saveDto.getAppendixSaveDtoList();
        if (appendixSaveDtoList.size() > 10) {
            throw new BusinessException("附件最多上传10个！");
        }
        appendixSaveDtoList.forEach(e -> {
            CustomCheckParamUtil.doCheck(e);
            e.setAppendixTypeId(saveDto.getAppendixTypeId());
            String attachmentId = e.getId();
            if (ObjectUtils.isEmpty(attachmentId)) {
                CaseAppendixRecord appendixRecord = new CaseAppendixRecord();
                appendixRecord.setCaseId(caseId);
                BeanUtils.copyProperties(e, appendixRecord);
                appendixRecord.setId(BaseUtil.createUid());
                appendixRecord.setCaseLinkCode(caseMainInfo.getCaseCurrentLinkCode());
                appendixRecord.setCaseLinkName(caseMainInfo.getCaseCurrentLinkName());
                appendixRecord.setCaseStageCode(caseMainInfo.getCaseCurrentStageCode());
                appendixRecord.setCaseStageName(caseMainInfo.getCaseCurrentStageName());
                appendixRecord.setDocumentCatalogCode("");
                if (!ObjectUtils.isEmpty(userInfo)) {
                    appendixRecord.setUploadUserId(userInfo.getUserId() + "");
                    appendixRecord.setUploadUserName(userInfo.getRealName());
                }
                appendixRecord.setUploadTime(LocalDateTime.now());
                appendixRecord.setAppendixUrl(e.getAppendixUrl());
                appendixRecord.setIsDelete(Constant.STRING_0);
                String suffix = e.getAppendixName().substring(e.getAppendixName().lastIndexOf(".") + 1);
                if (!suffix.equals(AttachmentRequestContentTypeEnum.png.getCode())
                        &&!suffix.equals(AttachmentRequestContentTypeEnum.jpg.getCode())
                        &&!suffix.equals(AttachmentRequestContentTypeEnum.pdf.getCode())) {
                    appendixRecord.setAppendixName(saveDto.getAppendixName()+"."+e.getAppendixUrl()
                            .substring(e.getAppendixUrl().lastIndexOf(".")+1));
                } else {
                    appendixRecord.setAppendixName(saveDto.getAppendixName());
                }
                caseAppendixRecordMapper.insertSelective(appendixRecord);
            }
        });
        return true;
    }

    /**
     * 描述：根据caseId获取关联附件列表
     *
     * @param caseId
     * @return List<FastCaseFileCommonInfoVo>
     * @author WangJie
     * @date 2022/12/05
     **/
    @Override
    public List<AppFastCaseFileCommonInfoVo> getAppFastCaseFileCommonListByCaseId(String caseId) {
        List<AppFastCaseFileCommonInfoVo> list = new ArrayList<>();
        Example queryExample = new Example(CaseAppendixRecord.class);
        queryExample.createCriteria().andEqualTo("caseId", caseId).andEqualTo("isDelete", Constant.STRING_0)
                .andNotEqualTo("appendixStatus",Constant.STRING_3);
        List<CaseAppendixRecord> caseDocumentRecords = caseAppendixRecordMapper.selectByExample(queryExample);
        caseDocumentRecords.forEach(e -> {
            AppFastCaseFileCommonInfoVo vo = new AppFastCaseFileCommonInfoVo();
            BeanUtils.copyProperties(e, vo);
            list.add(vo);
        });
        return list;
    }

    /**
     * 描述：根据caseId获取需要签字的文书记录
     *
     * @param caseId
     * @return List<AppFastCaseDocumentVo>
     * @author WangJie
     * @date 2022/12/05
     **/
    @Override
    public List<AppFastCaseDocumentVo> getAppFastCaseSignDocumentListByCaseId(String caseId) {
        List<AppFastCaseDocumentVo> list = new ArrayList<>();
        List<CaseDocumentRecordDto> caseDocumentRecords = caseDocumentRecordMapper.selectAppFastCaseSignDocumentListByCaseId(caseId);
        caseDocumentRecords.forEach(e -> {
            AppFastCaseDocumentVo vo = new AppFastCaseDocumentVo();
            BeanUtils.copyProperties(e, vo);
            list.add(vo);
        });
        return list;
    }

    /**
     * 移动端简案快办-接收文书签字捺印列表数据
     *
     * @param saveDto
     * @return Result
     * @author WangJie
     * @date 2022/12/05
     */
    @Override
    @Transactional(rollbackFor = {Error.class, Exception.class})
    public Result receiveSignFileList(AppFastCaseSignSaveDto saveDto) {
        if (!CollectionUtils.isEmpty(saveDto.getSignCommonDtoList())) {
            boolean isSuccess = true;
            List docResultList = new ArrayList();
            for (AppFastCaseSignCommonDto signCommonDto : saveDto.getSignCommonDtoList()) {
                Map docResultMap = new HashMap();
                CaseDocumentRecordSignSaveDto dto = new CaseDocumentRecordSignSaveDto();
                dto.setDocumentId(signCommonDto.getDocumentId());
                dto.setSignFile(saveDto.getSignFile());
                dto.setFingerprint(saveDto.getFingerprint());
                dto.setDocumentCatalogCode(signCommonDto.getDocumentCatalogCode());
                dto.setTemplateType(DocumentTemplateKindEnum.STANDARD_TEMPLATE.getCode());

                Map<String, Object> stringObjectMap = caseDocumentRecordService.receiveSignFileOfCaseDoc(dto);
                if (!"true".equals(stringObjectMap.get("success"))) {
                    isSuccess = false;
                    break;
                }
                docResultMap.put("documentCatalogCode", signCommonDto.getDocumentCatalogCode());
                docResultMap.put("pdfSealUrl", stringObjectMap.get("pdfSealUrl"));
                docResultList.add(docResultMap);

                HttpUtil.createGet(url.concat("/sign/doCaseRollByAppSignDoc?caseId="+saveDto.getCaseId()+"&documentCatalogCode="+signCommonDto.getDocumentCatalogCode())).execute().body();
            }

            if (!isSuccess) {
                return Result.error(Constant.STRING_SAVE_FAIL);
            } else {
                return Result.success(Constant.STRING_SAVE_SUCCESS);
            }
        }
        return Result.error("文书签字列表数据为空！");
    }

    /**
     * 【V1.10.0】描述：移动端简案快办-速结程序同意告知书 签名捺印
     *
     * @param saveDto
     * @return
     */
    @Override
    public CaseDocumentRecordDto receiveSignFileOfFastCaseAgreeDoc(CaseDocumentRecordSignSaveDto saveDto) {
        // 速结程序同意告知书 签名捺印
        CaseDocumentRecord record = caseDocumentRecordMapper.selectByPrimaryKey(saveDto.getDocumentId());
        if (Objects.isNull(record)) {
            throw new BusinessException("速结程序同意告知书不存在！");
        }
        // 查询立案审批文书 供前端提交审批
        CaseDocumentRecordDto approvalDocumentRecord = caseDocumentRecordMapper.getApprovalDocumentRecordByCaseId(saveDto);
        // 速结程序同意告知书已签名 无需再次签名
        if (DocumentStatusEnum.CONFIRM_END.getCode().equals(record.getDocumentSignstampedStatus())) {
            approvalDocumentRecord.setFastDocumentUrl(record.getDocumentUrlAfterSign());
            return approvalDocumentRecord;
        }
        saveDto.setCaseType(CaseTypeEnum.SIMPLE_QUICK.getCode());
        // 速结程序同意告知书签名
        Map<String, Object> objectMap = caseDocumentRecordService.receiveSignFileOfCaseDoc(saveDto);
        approvalDocumentRecord.setFastDocumentUrl(MapUtils.getString(objectMap, "pdfSealUrl"));
        return approvalDocumentRecord;
    }

    /**
     * 【V1.10.0】描述：立案登记（多案由、多当事人）
     *
     * @param saveDto
     * @return {@link Result }
     * @author cds
     * @date 2022/12/15
     */
    @Override
    public Result saveCaseRegister(CaseRegisterSaveDto saveDto) {
        Map<String, String> headers = HeaderUtil.headerInfo();
        String param = JSON.toJSONString(saveDto);
        String response = HttpUtil.createPost(url.concat("/punish/ucase/case/register/saveCaseRegister")).addHeaders(headers).body(param).execute().body();
        Result result = JSON.parseObject(response, Result.class);
        return result;
    }

    /**
     * 【V1.10.0】描述：暂存立案登记（多案由、多当事人）
     *
     * @param saveDto
     * @return {@link Result }
     * @author cds
     * @date 2022/12/15
     */
    @Override
    public Result saveCaseRegisterTemporary(CaseRegisterSaveDto saveDto) {
        Map<String, String> headers = HeaderUtil.headerInfo();
        String param = JSON.toJSONString(saveDto);
        String response = HttpUtil.createPost(url.concat("/punish/ucase/case/register/saveCaseRegisterTemporary")).addHeaders(headers).body(param).execute().body();
        return JSON.parseObject(response, Result.class);
    }

    /**
     * 【V1.10.0】描述：获取立案登记详情（多案由、多当事人）
     *
     * @param queryDto 查询dto
     * @return {@link Result<  CaseRegisterInfoVo  > }
     * @author cds
     * @date 2022/12/15
     */
    @Override
    public CaseRegisterInfoVo getCaseRegisterInfo(CaseRegisterDetailQueryDto queryDto) {
        Map<String, String> headers = HeaderUtil.headerInfo();
        String param = JSON.toJSONString(queryDto);
        String response = HttpUtil.createPost(url.concat("/punish/ucase/case/register/getCaseRegisterDetail")).addHeaders(headers).body(param).execute().body();
        Result result = JSON.parseObject(response, Result.class);
        if (HttpStatus.HTTP_OK != result.getCode()) {
            throw new BusinessException(result.getMessage());
        }
        return JSON.parseObject(JSONObject.toJSONString(result.getData()), CaseRegisterInfoVo.class);
    }

    /**
     * 【V1.10.0】描述：速结告知书生成 并返回前端文书地址
     *
     * @param caseId
     * @return
     * @author cds
     * @date 2022/12/15
     */
    @Override
    public FastNoticeDocumentDto generateFastNoticeDocument(String caseId) {
        CaseRegisterDetailQueryDto dto = new CaseRegisterDetailQueryDto();
        dto.setCaseId(caseId);
        String param = JSON.toJSONString(dto);
        Map<String, String> headers = HeaderUtil.headerInfo();
        String response = HttpUtil.createPost(url.concat("/punish/fast/case/register/getFastNoticeDocument")).addHeaders(headers).body(param).execute().body();
        Result result = JSON.parseObject(response, Result.class);
        if (HttpStatus.HTTP_OK != result.getCode()) {
            throw new BusinessException(result.getMessage());
        }
        return JSON.parseObject(JSONObject.toJSONString(result.getData()), FastNoticeDocumentDto.class);
    }

    /**
     * 获取处罚告知表单数据
     *
     * @param request
     * @return
     */
    @Override
    public Result<PunishInformFormVo> getPunishInformFormBaseinfo(InformHtmlRequest request) {
        Map<String, String> headers = HeaderUtil.headerInfo();
        String param = JSON.toJSONString(request);
        String response = HttpUtil.createPost(url.concat("/punish/inform/getPunishInformFormBaseinfo")).addHeaders(headers).body(param).execute().body();
        Result<PunishInformFormVo> result = JSON.parseObject(response, Result.class);
        return result;
    }

    /**
     * 保存处罚告知表单数据
     *
     * @param dto
     * @return
     */
    @Override
    public Result<String> savePunishInformForm(PunishInformFormDto dto) {
        Map<String, String> headers = HeaderUtil.headerInfo();
        String param = JSON.toJSONString(dto);
        String response = HttpUtil.createPost(url.concat("/punish/inform/savePunishInformForm")).addHeaders(headers).body(param).execute().body();
        Result<String> result = JSON.parseObject(response, Result.class);
        return result;
    }

    /**
     * 【AJ-V1.1.1】描述： 速结程序转普通程序
     *
     * @author: zhengqiang
     * @date: 2023/3/10
     * @param: caseId
     * @return {@link Result}
     **/
    @Override
    public Result changeToNormalProcedure(String caseId) {
        Map<String, String> headers = HeaderUtil.headerInfo();
        Map param = new HashMap();
        param.put("caseId", caseId);
        String response = HttpUtil.createGet(url.concat("/punish/fast/case/register/changeToNormalProcedure")).addHeaders(headers).form(param).execute().body();
        Result<String> result = JSON.parseObject(response, Result.class);
        return result;
    }

    /**
     * 【V1.4.1】描述：返回案件主流程当前环节的操作按钮-详情页底部，包括流程操作、下一步、更多操作
     * @param caseId
     * @return
     */
    @Override
    public Result<CaseCurrentLinkOperateVo> getCaseCurrentLinkOperate(String caseId) {
        Map<String, String> headers = HeaderUtil.headerInfo();
        Map param = new HashMap();
        param.put("caseId", caseId);
        String response = HttpUtil.createGet(url.concat("/punish/ucase/case/main/detail/getCaseCurrentLinkOperate")).addHeaders(headers).form(param).execute().body();
        Result<CaseCurrentLinkOperateVo> result = JSON.parseObject(response, Result.class);
        return result;
    }

    @Override
    public Result<ConfigFastProcedureVo> getTemplateByListCode(String orgCode, String listCode) {
        Map<String, String> headers = HeaderUtil.headerInfo();
        Map param = new HashMap();
        param.put("orgCode", orgCode);
        param.put("listCode", listCode);
        String response = HttpUtil.createGet(url.concat("/punish/config/fastCaseMatters/getTemplateByListCode")).addHeaders(headers).form(param).execute().body();
        Result<ConfigFastProcedureVo> result = JSON.parseObject(response, Result.class);
        return result;
    }

    /**
     * 【V1.11.4】描述： 修改移动端简案快办立案(处罚告知)相关文书
     *
     * @author: zhengqiang
     * @date: 2023/5/4
     * @param: modifyOfRegisterDto
     * @return {@link Result}
     **/
    @Override
    public Result modifyAppFastCaseRegisterDocuments(AppFastCaseDocumentModifyOfRegisterDto modifyOfRegisterDto) {
        Map<String, String> headers = HeaderUtil.headerInfo();
        String param = JSON.toJSONString(modifyOfRegisterDto);
        String response = HttpUtil.createPost(url.concat("/punish/fast/case/register/modifyAppFastCaseRegisterDocuments")).addHeaders(headers).body(param).execute().body();
        return JSON.parseObject(response, Result.class);
    }
    /**
     * 删除立案数据
     * @author lxj
     * @date  2022/2/22
     * @param  caseId 入参
     * @return  boolean
     **/
    @Override
    public Result delCaseSaveMsg(String caseId){
        Map<String, String> headers = HeaderUtil.headerInfo();
        Map param = new HashMap();

        String response = HttpUtil.createPost(url.concat("/punish/ucase/case/register/delCaseSaveMsg")).addHeaders(headers).body(caseId).execute().body();
        return JSON.parseObject(response, Result.class);
    }

    /**
     * 获取区划
     * @author lxj
     * @date  2022/3/21
     * @return
     **/
    @Override
    public Result<List<AreaVo>> getSysAreaList() {
        Map<String, String> headers = HeaderUtil.headerInfo();
        String response = HttpUtil.createGet(url.concat("/punish/common/getSysAreaList")).addHeaders(headers).execute().body();
        return JSON.parseObject(response, Result.class);
    }

    /**
     * 描述：获取证据采集信息
     *
     * @param caseId 用例id
     * @return {@link FastCaseEvidenceCollectInfoVo }
     * @author shishengyao
     * @date 2023/08/16
     */
    @Override
    public  Result<FastCaseEvidenceCollectInfoVo> getEvidenceCollectInfo(String caseId) {
        Map<String, String> headers = HeaderUtil.headerInfo();
        String response = HttpUtil.createGet(url.concat("/punish/fast/case/formSubmit/getEvidenceCollectInfo?caseId="+caseId)).addHeaders(headers).execute().body();
        return JSON.parseObject(response, Result.class);
    }


    /**
     * 描述：保存证据采集信息
     *
     * @param saveDto 保存dto
     * @return int
     * @author shishengyao
     * @date 2023/08/17
     */
    @Override
    public Result saveEvidenceCollectInfo(FastCaseEvidenceCollectInfoSaveDto saveDto) {
        Map<String, String> headers = HeaderUtil.headerInfo();
        String param = JSON.toJSONString(saveDto);
        String response = HttpUtil.createPost(url.concat("/punish/fast/case/formSubmit/saveEvidenceCollectInfo")).addHeaders(headers).body(param).execute().body();
        return JSON.parseObject(response, Result.class);
    }

    /**
     * 【V1.12.1】描述：简案快办立案登记
     *
     * @author: zhengqiang
     * @date: 2023/8/18
     * @param: saveDto
     * @return {@link Result<CaseRegisterSaveVo>}
     **/
    @Override
    public Result<CaseRegisterSaveVo> saveFastCaseRegister(FastCaseRegisterSaveDto saveDto) {
        return fastCaseRegisterClient.saveFastCaseRegister(saveDto);
    }

    /**
     * 【V1.12.1】描述： 查询简案快办暂存数据
     *
     * @author: zhengqiang
     * @date: 2023/8/18
     * @param: queryDto
     * @return {@link Result< FastCaseRegisterInfoVo>}
     **/
    @Override
    public Result<FastCaseRegisterInfoVo> getFastCaseRegisterInfo(FastCaseRegisterInfoQueryDto queryDto) {
        return fastCaseRegisterClient.getFastCaseRegisterInfo(queryDto);
    }

    /**
     * 【V1.12.1】描述： 生成简案快办文书
     *
     * @author: zhengqiang
     * @date: 2023/8/18
     * @param: dto
     * @return {@link Result<FastCaseNoticeDocumentVo>}
     **/
    @Override
    public Result<FastCaseNoticeDocumentVo> getFastCaseNoticeDocument(FastCaseRegisterInfoQueryDto dto) {
        return fastCaseRegisterClient.getFastCaseNoticeDocument(dto);
    }

    /**
     * 【V1.12.1】描述： 快办告知步骤操作(上一步,下一步)
     *
     * @author: zhengqiang
     * @date: 2023/8/18
     * @param: operateDto
     * @return {@link Result}
     **/
    @Override
    public Result saveFastInformOperateStep(FastCaseRegisterOperateDto operateDto) {
        return fastCaseRegisterClient.saveFastInformOperateStep(operateDto);
    }

    /**
     * 【V1.12.1】描述： 查询简案快办提示
     *
     * @author: zhengqiang
     * @date: 2023/8/17
     * @param: queryDto
     * @return {@link Result<String>}
     **/
    @Override
    public Result<String> getFastTipsByListCodeAndOrgCode(FastTipsQueryDto queryDto) {
        return fastCaseRegisterClient.getFastTipsByListCodeAndOrgCode(queryDto);
    }

    /**
     * 【V1.12.1】描述： 根据用户查询简案快办最新的一条暂存数据
     *
     * @author: zhengqiang
     * @date: 2023/8/18
     * @return {@link Result<  AppFastCaseRegisterTempVo >}
     **/
    @Override
    public Result<AppFastCaseRegisterTempVo> getFastRegisterTempByUser() {
        UserDTO userInfo = UserUtil.getUserInfo();
        if (null == userInfo) {
            throw new BusinessException("登录失效");
        }
        String userId = userInfo.getUserId().toString();
        String orgCode = userInfo.getOrgCode();
        AppFastCaseRegisterTempVo registerTempVo = caseMainInfoMapper.selectFastRegisterTempByUser(userId, orgCode);
        return Result.success(registerTempVo);
    }

    /**
     * 【V1.12.1】描述： 获取简案快办处罚事项
     *
     * @author: zhengqiang
     * @date: 2023/8/23
     * @param: orgCode
     * @return {@link Result<List< PunishItemVo>>}
     **/
    @Override
    public Result<List<PunishItemVo>> getFastAuditPubishTreeByOrgCode(String orgCode) {
        return fastCaseRegisterClient.getFastAuditPubishTreeByOrgCode(orgCode);
    }

    /**
     * 【V1.12.1】描述： 获取自动结案提醒
     *
     * @author: zhengqiang
     * @date: 2023/8/23
     * @param: caseId
     * @return {@link FastAutoCloseCaseReminderVo}
     **/
    @Override
    public FastAutoCloseCaseReminderVo getAutoCloseCaseReminder(String caseId) {
        Result<FastAutoCloseCaseReminderVo> result = fastCaseRegisterClient.getAutoCloseCaseReminder(caseId);
        if (ObjectUtil.isNotEmpty(result) && HttpStatus.HTTP_OK == result.getCode()) {
            return result.getData();
        }
        return null;
    }

    /**
     * 【V1.12.1】 保存简案快办调查终结
     *
     * @param fastCaseAddInfoDto 快速添加信息dto
     * @return {@link Result<String> }
     * @author shishengyao
     * @date 2023/08/24
     */
    @Override
    public Result<String> saveInvestigateEnd(FastCaseFormSubmitAddInfoDto fastCaseAddInfoDto){
        Map<String, String> headers = HeaderUtil.headerInfo();
        String param =JSON.toJSONStringWithDateFormat(fastCaseAddInfoDto,"yyyy-MM-dd HH:mm",SerializerFeature.WriteDateUseDateFormat);
        String response = HttpUtil.createPost(url.concat("/punish/fast/case/formSubmit/saveInvestigateEnd")).addHeaders(headers).body(param).execute().body();
        return JSON.parseObject(response, Result.class);
    }

    /**
     * 【V1.12.1】  描述：简案快办调查终结暂存信息获取
     *
     * @param dto dto
     * @return {@link Result<FastCaseFormSubmitAddInfoDto> }
     * @author shishengyao
     * @date 2023/08/24
     */
    @Override
    public Result<FastCaseFormSubmitAddInfoDto> getInvestigateEndTemporary(FastCaseAddInfoTemporaryDto dto){
        Map<String, String> headers = HeaderUtil.headerInfo();
        String param = JSON.toJSONString(dto);
        String response = HttpUtil.createPost(url.concat("/punish/fast/case/formSubmit/getInvestigateEndTemporary")).addHeaders(headers).body(param).execute().body();
        return JSON.parseObject(response, Result.class);
    }


    /**
     * 【V1.12.1】描述：返回简案快办案件主流程当前环节的顶部按钮
     *
     * @author: zhengqiang
     * @date: 2023/8/25
     * @param: caseId
     * @return {@link Result< List< CaseCurrentLinkMoreOperateVo>>}
     **/
    @Override
    public Result<List<CaseCurrentLinkMoreOperateVo>> getAppFastCaseCurrentLinkOperate(String caseId) {
        CaseMainInfo caseMainInfo = caseMainInfoMapper.selectByPrimaryKey(caseId);
        String caseCurrentStageName = caseMainInfo.getCaseCurrentStageName();
        String caseCurrentLinkName = caseMainInfo.getCaseCurrentLinkName();
        List<CaseCurrentLinkMoreOperateVo> fastCaseOperateList = new ArrayList<>();
        //获取更多操作配置
        Result<CaseCurrentLinkOperateVo> caseCurrentLinkOperateVoResult = caseMainInfoService.doGetCaseCurrentLinkOperate(caseId);
        if (ObjectUtil.isNotEmpty(caseCurrentLinkOperateVoResult) && ObjectUtil.isNotEmpty(caseCurrentLinkOperateVoResult.getData())) {
            CaseCurrentLinkOperateVo caseCurrentLinkOperateVo = JSON.parseObject(JSONObject.toJSONString(caseCurrentLinkOperateVoResult.getData()), CaseCurrentLinkOperateVo.class);
            List<CaseCurrentLinkMoreOperateVo> currentLinkMoreOperateVoList = caseCurrentLinkOperateVo.getCurrentLinkMoreOperateVoList();
            if (ObjectUtil.isNotEmpty(currentLinkMoreOperateVoList)) {
                for (CaseCurrentLinkMoreOperateVo operateVo : currentLinkMoreOperateVoList) {
                    //获取转正常流程
                    if ("009".equals(operateVo.getFrontSymble())) {
                        operateVo.setOperateCode("toNormal");
                        fastCaseOperateList.add(operateVo);
                    }
                }
            }
        }
        //非审批中, 显示附件上传按钮
        if (ObjectUtil.isNotEmpty(caseCurrentLinkName) && !caseCurrentLinkName.contains("审批")) {
            CaseCurrentLinkMoreOperateVo upload = new CaseCurrentLinkMoreOperateVo();
            upload.setOperateCode("upload");
            upload.setOperateName("附件上传");
            fastCaseOperateList.add(upload);
        }

        //简案快办未提交前显示更多操作(删除案件)按钮
        if (CaseStageEnum.CASE_REGISTER.getDes().equals(caseCurrentStageName) || "暂存".equals(caseCurrentStageName)
                || "处罚告知".equals(caseCurrentLinkName) || "不予处罚告知".equals(caseCurrentLinkName)) {
            CaseCurrentLinkMoreOperateVo upload = new CaseCurrentLinkMoreOperateVo();
            upload.setOperateCode("moreOperate");
            upload.setOperateName("更多操作");
            fastCaseOperateList.add(upload);
        }
        return Result.success(fastCaseOperateList);
    }

    @Override
    public Result saveFastCaseAutoEnd(FastCaseAutoEndSaveDto saveDto) {
        Map<String, String> headers = HeaderUtil.headerInfo();
        String param = JSON.toJSONString(saveDto);
        String response = HttpUtil.createPost(url.concat("/punish/fast/case/end/saveFastCaseAutoEnd")).addHeaders(headers).body(param).execute().body();
        return JSON.parseObject(response, Result.class);
    }

    /**
     * 【V1.12.1】描述： 上传放弃陈述申辩文件（简案快办）
     *
     * @author: zhengqiang
     * @date: 2023/8/29
     * @param: saveDto
     * @return {@link Result< String>}
     **/
    @Transactional(rollbackFor = {Error.class, Exception.class})
    @Override
    public Result<String> uploadWaiverPleaFile(AppWaiverPleaFileSaveDto saveDto) {
        UserDTO userInfo = UserUtil.getUserInfo();
        if (ObjectUtil.isEmpty(userInfo)) {
            throw new BusinessException("未登录或登录信息已失效");
        }
        CaseMainInfo caseMainInfo = caseMainInfoMapper.selectByPrimaryKey(saveDto.getCaseId());
        //查询文书目录信息
        ConfigBusiParamDocumentInfo configBusiParam = configBusiParamDocumentInfoService.getDetailByDocumentCatalogCode(saveDto.getDocumentCatalogCode());
        String documentKindCode = configBusiParam.getDocumentKindCode();
        if (!DocumentKindEnum.DOC_KIND_DK2FQCSSBSM.getCode().equals(documentKindCode)) {
            throw new BusinessException("文书目录编码有误");
        }
        //案件环节校验
        if (!"放弃陈述申辩".equals(caseMainInfo.getCaseCurrentLinkName())) {
            throw new BusinessException("当前环节不允许上传陈述申辩文件");
        }
        //删除之前的上传放弃陈述申辩文件
        Example offDoc = new Example(CaseOfflineDocumentRecord.class);
        offDoc.createCriteria().andEqualTo("caseId", saveDto.getCaseId())
                .andEqualTo("documentCatalogCode", saveDto.getDocumentCatalogCode())
                .andEqualTo("status", Constant.STRING_1);
        CaseOfflineDocumentRecord updateOfflineDocumentRecord = new CaseOfflineDocumentRecord();
        updateOfflineDocumentRecord.setStatus(Constant.STRING_3);
        caseOfflineDocumentRecordMapper.updateByExampleSelective(updateOfflineDocumentRecord, offDoc);

        CaseOfflineDocumentRecord offlineDocumentRecord = new CaseOfflineDocumentRecord();
        offlineDocumentRecord.setCaseId(saveDto.getCaseId());

        offlineDocumentRecord.setDocumentKindCode(configBusiParam.getDocumentKindCode());
        offlineDocumentRecord.setDocumentKindName(configBusiParam.getDocumentKindName());
        offlineDocumentRecord.setDocumentTittle(configBusiParam.getDocumentKindName());
        offlineDocumentRecord.setDocumentCatalogCode(configBusiParam.getDocumentCatalogCode());

        offlineDocumentRecord.setDocumentUrl(saveDto.getAppendixUrl());
        String appendixName = saveDto.getAppendixName();
        offlineDocumentRecord.setAppendixName(appendixName);
        if (appendixName.lastIndexOf(Constant.STRING_POINT) > -1) {
            String appendixNamePrefix = appendixName.substring(0, appendixName.lastIndexOf(Constant.STRING_POINT));
            String appendixNameSuffix = appendixName.substring(appendixName.lastIndexOf(Constant.STRING_POINT) + 1);
            offlineDocumentRecord.setAppendixNamePrefix(appendixNamePrefix);
            offlineDocumentRecord.setAppendixNameSuffix(appendixNameSuffix);
        }
        offlineDocumentRecord.setDocumentType(DocumentTypeEnum.LAW_DOCUMENT.getCode());
        offlineDocumentRecord.setCaseLinkCode(caseMainInfo.getCaseCurrentLinkCode());
        offlineDocumentRecord.setCaseLinkName(caseMainInfo.getCaseCurrentLinkName());
        offlineDocumentRecord.setCaseStageCode(caseMainInfo.getCaseCurrentStageCode());
        offlineDocumentRecord.setCaseStageName(caseMainInfo.getCaseCurrentStageName());
        offlineDocumentRecord.setCreateUserId(userInfo.getUserId().toString());
        offlineDocumentRecord.setCreateUserName(userInfo.getRealName());
        offlineDocumentRecord.setStatus(Constant.STRING_1);
        offlineDocumentRecord.setId(StringUtils.uuid());
        offlineDocumentRecord.setCreateTime(LocalDateTime.now());
        int i = caseOfflineDocumentRecordMapper.insertSelective(offlineDocumentRecord);
        if (i > 0) {
            //上传放弃陈述申辩成功, 调用流程滚动接口
            HttpUtil.createGet(url.concat("/sign/doCaseRollByAppSignDoc?caseId=" + saveDto.getCaseId() + "&documentCatalogCode=" + saveDto.getDocumentCatalogCode())).execute().body();

            return Result.success(Constant.STRING_OPERATE_SUCCESS);
        }
        return Result.error(Constant.STRING_OPERATE_FAIL);
    }


    /**
     * 描述：保存证据采集信息
     *
     * @param orgCode  组织代码
     * @param listCode 代码列表
     * @param caseId   用例id
     * @return {@link Result<List<ConfigFastProcedureDocumentInfoVo>> }
     * @author shishengyao
     * @date 2023/09/04
     */
    @Override
    public Result<List<ConfigFastProcedureDocumentInfoVo>> getDocumentTemplateByListCode(String orgCode, String listCode, String caseId) {
        Map<String, String> headers = HeaderUtil.headerInfo();
        Map<String, Object> urlParam = new HashMap<>(3);
        urlParam.put("orgCode",orgCode);
        urlParam.put("listCode",listCode);
        urlParam.put("caseId",caseId);
        String response = HttpUtil.createGet(url.concat("punish/config/fastProcedure/getDocumentTemplateByListCode")).addHeaders(headers).form(urlParam).execute().body();
        return JSON.parseObject(response, Result.class);
    }

    @Override
    public Result<String> delEvidenceCollectInfo(FastCaseEvidenceCollectInfoDeleteDto dto) {
        Map<String, String> headers = HeaderUtil.headerInfo();
        String param = JSON.toJSONString(dto);
        String response = HttpUtil.createPost(url.concat("/punish/fast/case/formSubmit/delEvidenceCollectInfo")).addHeaders(headers).body(param).execute().body();
        return JSON.parseObject(response, Result.class);
    }
    /**
     * 描述：案件撤回操作
     *
     * @param caseId  案件id
     * @param caseLinkCode 流程编码
     * @author lujiayu
     * @date 2023/12/11
     */
    @Override
    public Result<String> doRecallCaseHandleLink(String caseId, String caseLinkCode) {
        Map<String, String> headers = HeaderUtil.headerInfo();
        Map<String, Object> urlParam = new HashMap<>(2);
        urlParam.put("caseId",caseId);
        urlParam.put("caseLinkCode",caseLinkCode);
        String response = HttpUtil.createGet(url.concat("/punish/ucase/case/main/doRecallCaseHandleLink")).addHeaders(headers).form(urlParam).execute().body();
        return JSON.parseObject(response, Result.class);
    }

    @Override
    public Result<String> getIsNeedHearingResult(PunishInformFormDto punishInformFormDto) {
        Map<String, String> headers = HeaderUtil.headerInfo();
        String param = JSON.toJSONString(punishInformFormDto);
        String response = HttpUtil.createPost(url.concat("punish/inform/getIsNeedHearingResult")).addHeaders(headers).body(param).execute().body();
        Result<String> result = JSON.parseObject(response, Result.class);
        return result;
    }

    /**
     * 描述：查询案件废弃文书接口
     *
     * @param caseId  案件id
     * @author lujiayu
     * @date 2023/12/11
     */
    @Override
    public Result<List<AppInvalidCaseDetailDocumentInfoVo>> getInvalidCaseDetailDocumentInfoList(String caseId) {
        if (StringUtils.isNotEmpty(caseId)) {
            List<AppInvalidCaseDetailDocumentInfoVo> list = new ArrayList<>();
            Example example = new Example(CaseDocumentRecord.class);
            example.createCriteria().andEqualTo("caseId", caseId)
                    .andEqualTo("documentRecordStatus", Constant.STRING_3);
            example.orderBy("documentCreateTime").desc();
            List<CaseDocumentRecord> caseDocumentRecords = caseDocumentRecordMapper.selectByExample(example);
            if (caseDocumentRecords!= null && caseDocumentRecords.size() > 0) {
                caseDocumentRecords.forEach(e -> {
                    AppInvalidCaseDetailDocumentInfoVo vo = new AppInvalidCaseDetailDocumentInfoVo();
                    String documentCatalogCode = e.getDocumentCatalogCode();
                    if (StringUtils.isNotEmpty(documentCatalogCode)) {
                        Example configBusiParamDocumentInfoExample = new Example(ConfigBusiParamDocumentInfo.class);
                        configBusiParamDocumentInfoExample.createCriteria().andEqualTo("documentCatalogCode",documentCatalogCode);
                        List<ConfigBusiParamDocumentInfo> configBusiParamDocumentInfos = configBusiParamDocumentInfoMapper.selectByExample(configBusiParamDocumentInfoExample);
                        if (configBusiParamDocumentInfos!= null && configBusiParamDocumentInfos.size() > 0) {
                            ConfigBusiParamDocumentInfo configBusiParamDocumentInfo = configBusiParamDocumentInfos.get(Constant.INTEGER_0);
                            vo.setDocumentKindName(configBusiParamDocumentInfo.getDocumentKindName());
                            vo.setDocumentKindCode(configBusiParamDocumentInfo.getDocumentKindCode());
                        }
                    }
                    BeanUtils.copyProperties(e, vo);
                    list.add(vo);
                });
            }
            return Result.success(Constant.STRING_GET_SUCCESS,list);
        }
        return Result.error("案件id不能为空");
    }

    /**
     * 描述：附件删除操作
     *
     * @param caseAppendixDeleteDto  需要删除的附件的dto
     * @author lujiayu
     * @date 2023/12/11
     */
    @Override
    public Result<String> deleteCaseAttachmentInfo(CaseAppendixDeleteDto caseAppendixDeleteDto) {
        String caseId = caseAppendixDeleteDto.getCaseId();
        String appendixId = caseAppendixDeleteDto.getAppendixId();
        if (StringUtils.isNotEmpty(caseId) && StringUtils.isNotEmpty(appendixId)) {
            Example example = new Example(CaseAppendixRecord.class);
            example.createCriteria().andEqualTo("caseId", caseId)
                   .andEqualTo("id", appendixId);
            List<CaseAppendixRecord> caseAppendixRecords = caseAppendixRecordMapper.selectByExample(example);
            if (!CollectionUtils.isEmpty(caseAppendixRecords)) {
                CaseAppendixRecord caseAppendixRecord = caseAppendixRecords.get(Constant.INTEGER_0);
                if (!Constant.STRING_1.equals(caseAppendixRecord.getIsDelete())) {
                    caseAppendixRecord.setIsDelete(Constant.STRING_1);
                    caseAppendixRecordMapper.updateByPrimaryKeySelective(caseAppendixRecord);
                    return Result.success(Constant.STRING_OPERATE_SUCCESS);
                } else {
                    return Result.error("附件已被删除");
                }
            }
        }
        return Result.error(Constant.STRING_OPERATE_FAIL);
    }

    @Override
    public Result<ConfigPoliceAdjudicationVo> getPoliceAdjudication(String itemRelationCode) {
        if (StringUtils.isNotEmpty(itemRelationCode)) {
            Map<String, String> headers = HeaderUtil.headerInfo();
            Map<String, Object> urlParam = new HashMap<>(2);
            urlParam.put("itemRelationCode",itemRelationCode);
            String response = HttpUtil.createGet(url.concat("punish/config/policeAdjudication/getByItemRelationCode")).addHeaders(headers).form(urlParam).execute().body();
            return JSON.parseObject(response, Result.class);
        }
        return Result.error("事项代码不能为空");
    }
}
